<template>
  <a-layout style="min-height: 100vh; background: #f5f7fa;">
    <!-- 简单导航 -->
    <a-layout-header style="background: #ffffff; padding: 0 50px; box-shadow: 0 1px 4px rgba(0,0,0,0.08);">
      <div style="display: flex; align-items: center; justify-content: space-between;">
        <div style="font-size: 20px; font-weight: 600; color: #2c3e50;">
          🧬 {{ $t('home.title') }}
        </div>
        <!-- 语言切换 -->
        <a-dropdown>
          <a-button>
            <template #icon><global-outlined /></template>
            {{ currentLanguage }}
          </a-button>
          <template #overlay>
            <a-menu @click="handleLanguageChange">
              <a-menu-item key="zh">
                <span :style="{ fontWeight: locale === 'zh' ? 'bold' : 'normal' }">
                  🇨🇳 中文
                </span>
              </a-menu-item>
              <a-menu-item key="en">
                <span :style="{ fontWeight: locale === 'en' ? 'bold' : 'normal' }">
                  🇺🇸 English
                </span>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </a-layout-header>

    <a-layout-content style="padding: 80px 50px; display: flex; align-items: center; justify-content: center;">
      <a-card style="width: 450px; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.1);">
        <template #title>
          <div style="text-align: center; padding: 20px 0;">
            <h2 style="margin: 0; color: #2c3e50; font-size: 24px;">🔐 {{ $t('login.title') }}</h2>
            <p style="margin: 8px 0 0 0; color: #909399; font-size: 14px;">{{ $t('login.subtitle') }}</p>
          </div>
        </template>

        <a-spin :spinning="loading">
          <!-- 步骤1: 获取验证码 -->
          <div v-if="step === 1">
            <a-alert
              :message="$t('login.verificationInfo')"
              :description="$t('login.verificationDesc', { email: adminEmail ? ': ' + adminEmail : '' })"
              type="info"
              show-icon
              style="margin-bottom: 24px;"
            />

            <a-button
              type="primary"
              size="large"
              block
              :loading="sending"
              @click="sendCode"
              style="height: 48px; font-size: 16px;"
            >
              <template #icon><mail-outlined /></template>
              {{ sending ? $t('login.sending') : $t('login.getCode') }}
            </a-button>

            <div style="margin-top: 16px; text-align: center;">
              <a-button type="link" @click="$router.push('/')">
                {{ $t('login.backHome') }}
              </a-button>
            </div>
          </div>

          <!-- 步骤2: 输入验证码 -->
          <div v-if="step === 2">
            <a-alert
              :message="$t('login.codeSent')"
              :description="$t('login.codeSentDesc', { email: adminEmail ? ': ' + adminEmail : '' })"
              type="success"
              show-icon
              style="margin-bottom: 24px;"
            />

            <!-- 开发模式显示验证码 -->
            <a-alert
              v-if="devCode"
              :message="$t('login.devModeCode', { code: devCode })"
              type="warning"
              show-icon
              style="margin-bottom: 24px;"
            />

            <a-form :model="form" @finish="verifyCode">
              <!-- 验证码输入框组 -->
              <a-form-item
                name="code"
                :rules="[{ required: true, message: $t('login.codeRequired') }]"
              >
                <div class="verification-code-container">
                  <input
                    v-for="(item, index) in 6"
                    :key="index"
                    :ref="el => setInputRef(el, index)"
                    v-model="codeDigits[index]"
                    type="text"
                    maxlength="1"
                    class="code-input"
                    :class="{ 'has-value': codeDigits[index] }"
                    @input="handleInput(index, $event)"
                    @keydown="handleKeyDown(index, $event)"
                    @paste="handlePaste($event)"
                    @focus="handleFocus(index)"
                  />
                </div>
              </a-form-item>

              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                  size="large"
                  block
                  :loading="verifying"
                  style="height: 48px; font-size: 16px;"
                >
                  {{ $t('login.verifyAndLogin') }}
                </a-button>
              </a-form-item>
            </a-form>

            <div style="text-align: center; margin-top: 16px;">
              <a-space>
                <a-button type="link" @click="sendCode" :disabled="countdown > 0">
                  {{ countdown > 0 ? $t('login.resendCountdown', { count: countdown }) : $t('login.getCodeAgain') }}
                </a-button>
                <a-button type="link" @click="step = 1">
                  {{ $t('login.backStep') }}
                </a-button>
              </a-space>
            </div>
          </div>
        </a-spin>
      </a-card>
    </a-layout-content>

    <a-layout-footer style="text-align: center; background: #ffffff; color: #606266; border-top: 1px solid #e4e7ed;">
      <div style="padding: 16px 0;">
        <p style="margin: 0;">{{ $t('home.footer.copyright') }}</p>
      </div>
    </a-layout-footer>
  </a-layout>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { MailOutlined, SafetyOutlined, GlobalOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import config from '../config/env'

const router = useRouter()
const { locale, t } = useI18n()
const step = ref(1)
const loading = ref(false)
const sending = ref(false)
const verifying = ref(false)
const adminEmail = ref('')
const devCode = ref('')
const countdown = ref(0)

// 验证码输入框相关
const codeDigits = reactive(['', '', '', '', '', ''])
const inputRefs = ref([])

const form = reactive({
  code: ''
})

let countdownTimer = null

// 设置输入框ref
const setInputRef = (el, index) => {
  if (el) {
    inputRefs.value[index] = el
  }
}

// 监听codeDigits变化,同步到form.code
watch(codeDigits, (newDigits) => {
  form.code = newDigits.join('')
}, { deep: true })

const currentLanguage = computed(() => {
  return locale.value === 'zh' ? '中文' : 'English'
})

const handleLanguageChange = ({ key }) => {
  locale.value = key
  localStorage.setItem('language', key)
  message.success(key === 'zh' ? '已切换到中文' : 'Switched to English')
}

// 处理输入
const handleInput = (index, event) => {
  const value = event.target.value
  
  // 只允许数字
  if (value && !/^\d$/.test(value)) {
    codeDigits[index] = ''
    return
  }
  
  codeDigits[index] = value
  
  // 如果输入了数字,自动跳转到下一个输入框
  if (value && index < 5) {
    nextTick(() => {
      inputRefs.value[index + 1]?.focus()
    })
  }
}

// 处理键盘事件
const handleKeyDown = (index, event) => {
  // 退格键:删除当前内容并跳到上一个
  if (event.key === 'Backspace' && !codeDigits[index] && index > 0) {
    nextTick(() => {
      inputRefs.value[index - 1]?.focus()
    })
  }
  // 左箭头
  else if (event.key === 'ArrowLeft' && index > 0) {
    event.preventDefault()
    inputRefs.value[index - 1]?.focus()
  }
  // 右箭头
  else if (event.key === 'ArrowRight' && index < 5) {
    event.preventDefault()
    inputRefs.value[index + 1]?.focus()
  }
}

// 处理粘贴
const handlePaste = (event) => {
  event.preventDefault()
  const pasteData = event.clipboardData?.getData('text') || ''
  const digits = pasteData.replace(/\D/g, '').slice(0, 6).split('')
  
  digits.forEach((digit, index) => {
    if (index < 6) {
      codeDigits[index] = digit
    }
  })
  
  // 聚焦到最后一个填充的输入框或下一个空输入框
  nextTick(() => {
    const nextEmptyIndex = codeDigits.findIndex(d => !d)
    const focusIndex = nextEmptyIndex === -1 ? 5 : nextEmptyIndex
    inputRefs.value[focusIndex]?.focus()
  })
}

// 处理聚焦
const handleFocus = (index) => {
  // 选中当前内容,方便替换
  nextTick(() => {
    inputRefs.value[index]?.select()
  })
}

const sendCode = async () => {
  sending.value = true
  try {
    const response = await axios.post(`${config.API_BASE_URL}/auth/send-code`)
    
    if (response.data.success) {
      message.success(response.data.message)
      adminEmail.value = response.data.email || ''
      devCode.value = response.data.code || ''  // 开发模式显示验证码
      step.value = 2
      
      // 重置验证码输入框
      codeDigits.forEach((_, index) => {
        codeDigits[index] = ''
      })
      
      // 自动聚焦到第一个输入框
      nextTick(() => {
        inputRefs.value[0]?.focus()
      })
      
      // 开始倒计时（60秒）
      countdown.value = 60
      if (countdownTimer) clearInterval(countdownTimer)
      countdownTimer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(countdownTimer)
        }
      }, 1000)
    }
  } catch (error) {
    console.error(t('login.sendCodeError'), error)
    message.error(t('login.sendCodeError') + ': ' + (error.response?.data?.detail || error.message))
  } finally {
    sending.value = false
  }
}

const verifyCode = async () => {
  if (!form.code || form.code.length !== 6) {
    message.error(t('login.codeRequired'))
    return
  }

  verifying.value = true
  try {
    const response = await axios.post(`${config.API_BASE_URL}/auth/verify-code`, {
      code: form.code
    })
    
    if (response.data.success) {
      // 保存token
      localStorage.setItem('admin_token', response.data.token)
      localStorage.setItem('token_expires', Date.now() + response.data.expires_in * 1000)
      
      message.success(t('login.loginSuccess'))
      
      // 跳转到上传页面
      setTimeout(() => {
        router.push('/upload')
      }, 500)
    }
  } catch (error) {
    console.error(t('login.verifyError'), error)
    message.error(t('login.verifyError') + ': ' + (error.response?.data?.detail || error.message))
    // 清空验证码输入框
    codeDigits.forEach((_, index) => {
      codeDigits[index] = ''
    })
    // 重新聚焦到第一个输入框
    nextTick(() => {
      inputRefs.value[0]?.focus()
    })
  } finally {
    verifying.value = false
  }
}
</script>

<style scoped>
:deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
}

:deep(.ant-btn-primary) {
  background: #409eff;
  border-color: #409eff;
  border-radius: 8px;
}

:deep(.ant-btn-primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

/* 验证码输入框容器 */
.verification-code-container {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding: 20px 0;
}

/* 单个验证码输入框 */
.code-input {
  width: 50px;
  height: 60px;
  text-align: center;
  font-size: 28px;
  font-weight: 600;
  border: 2px solid #d9d9d9;
  border-radius: 8px;
  outline: none;
  transition: all 0.3s ease;
  background-color: #fafafa;
  color: #2c3e50;
  caret-color: #409eff;
}

/* 聚焦状态 */
.code-input:focus {
  border-color: #409eff;
  background-color: #ffffff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}

/* 已输入状态 */
.code-input.has-value {
  border-color: #409eff;
  background-color: #e6f7ff;
}

/* 禁用状态 */
.code-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 0.6;
}

/* 悬停效果 */
.code-input:hover:not(:disabled) {
  border-color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 576px) {
  .code-input {
    width: 42px;
    height: 52px;
    font-size: 24px;
  }
  
  .verification-code-container {
    gap: 8px;
  }
}
</style>
